<script setup lang="ts">
import {
  aspectType,
  EnumAllViewType,
  EnumOpTypes,
  loadSingleViewType,
  opMsgType
} from '@renderer/views/imgViewer/imgTypes'
import OpBtnContainer from '@renderer/views/imgViewer/components/opBtn/OpBtnContainer.vue'
import SingleViewer from '@renderer/views/imgViewer/components/SingleViewer.vue'
import { inject, onMounted, provide, ref } from 'vue'
import axios from 'axios'
import RenderOptions from '@renderer/views/imgViewer/3d/RenderOptions.vue'
import { useRouter } from 'vue-router'

const imgSrcRef = ref('')
const statusRef = ref({
  isWaitingFirstImg: true
})

const { ioInstance, baseUri, throughGatewayFlag, sendMsg } = inject('pyImgHandlerIo') as any
provide('windowId', 'volume')
provide('viewType', EnumAllViewType.volume)
const aspectRef = ref<any>(null)
const setAspect = async (args: aspectType) => {
  const { width, height } = args
  aspectRef.value = {
    width,
    height
  }
  handleAspectChange(width, height)
}

const handleAspectChange = (width: number, height: number) => {
  if (statusRef.value.isWaitingFirstImg) {
    setAspect2Server()
    return
  }
  const msg = {
    viewType: EnumAllViewType.volume,
    opType: 'resize',
    size: {
      [EnumAllViewType.volume]: {
        width: width,
        height: height
      }
    }
  }
  sendMsg(msg)
}

const setAspect2Server = async () => {
  const msg: loadSingleViewType = {
    viewType: EnumAllViewType.volume,
    opType: EnumOpTypes.setSize,
    size: aspectRef.value
  }
  const prefix = throughGatewayFlag ? `${baseUri}/image/` : `${baseUri}/`
  await axios.post(`${prefix}setSize`, msg)
}

ioInstance.on('image', (data) => {
  console.log('收到volume img')
  if (data.volume) {
    statusRef.value.isWaitingFirstImg = false
    imgSrcRef.value = `${data.volume.img}`
  }
})

const router = useRouter()

const goStack = () => {
  router.push({
    name: 'stack'
  })
}
const goMpr = () => {
  router.push({
    name: 'mpr'
  })
}

const handleReset = (subResetType: string) => {
  const msg: opMsgType = {
    viewType: EnumAllViewType.volume,
    opType: 'reset',
    subOpType: subResetType
  }
  sendMsg(msg)
}
</script>

<template>
  <div class="w-full h-full flex flex-col">
    <render-options class="w-full h-[50px] flex items-center" />
    <div class="w-full flex">
      <div class="w-[500px] h-[500px] justify-center">
        <single-viewer
          :view-type="EnumAllViewType.volume"
          @set-aspect="(args) => setAspect(args as aspectType)"
          :img-src="imgSrcRef"
        />
      </div>
      <div class="w-[100px] h-full flex flex-col ml-auto">
        <op-btn-container @reset="handleReset" />
        <el-button @click="goStack">Stack View</el-button>
        <el-button class="!ml-0" @click="goMpr">Mpr View</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
